package org.cttic.visualization.visualization.websocket;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.cttic.visualization.visualization.websocket.vo.WebsocketModal;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDateTime;

@Component
@ServerEndpoint(value = "/ws")
@Slf4j
public class WebSocket implements ApplicationContextAware {

    private static StringRedisTemplate stringRedisTemplate;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        stringRedisTemplate = (StringRedisTemplate) applicationContext.getBean("stringRedisTemplate");
    }


    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        JSONObject json = JSONUtil.parseObj(message);
        log.info("=========>websocket请求消息：{}",message);
        if ("114".equals(json.getStr("cmd"))) {
            if (json.getBool("onOff")) {
                if(json.getStr("provinceId").length() ==2){
                    WebsocketModal wsm = new WebsocketModal();
                    wsm.setHttpSessionId(json.getStr("sessionId"));
                    wsm.setProvinceId(json.getStr("provinceId"));
                    wsm.setSession(session);
                    wsm.setOnOff(json.getBool("onOff"));
                    stringRedisTemplate.opsForSet().add(Data.websocketPre, session.getId());
                    Data.sessionMap.put(session.getId(), wsm);
                    JSONObject put = new JSONObject().put("cmd", "114")
                        .put("msg","连接成功")
                        .put("receiveTime", LocalDateTime.now());
                    session.getBasicRemote().sendText(put.toString());
                }else {
                    JSONObject put = new JSONObject().put("cmd", "114")
                        .put("msg","省编码不正确")
                        .put("receiveTime", LocalDateTime.now());
                    session.getBasicRemote().sendText(put.toString());
                }
            }else {
                JSONObject put = new JSONObject().put("cmd", "114")
                    .put("msg","连接成功")
                    .put("receiveTime", LocalDateTime.now());
                session.getBasicRemote().sendText(put.toString());
            }
        } else if ("199".equals(json.getStr("cmd"))) {
            WebsocketModal websocketModal = Data.sessionMap.get(session.getId());
            if(websocketModal == null){
                session.getBasicRemote().sendText("请先登录");
            }else {
                websocketModal.setFrequence(json.getStr("frequence"));
                JSONObject put = new JSONObject().put("cmd", "199").put("receiveTime", LocalDateTime.now());
                session.getBasicRemote().sendText(put.toString());
            }
        }


    }


    @OnOpen
    public void onOpen(Session session) throws Exception {
        log.info("websocket.id={}建立连接", session.getId());

    }


    @OnClose
    public void onClose(Session session) {

        if (Data.sessionMap.containsKey(session.getId())) {
            Data.sessionMap.remove(session.getId());
        }
        stringRedisTemplate.opsForSet().remove(Data.websocketPre,session.getId());
        log.info("id={}关闭链接", session.getId());
    }


    @OnError
    public void OnError(Session session, Throwable throwable) {
        log.error("{} 链接异常,{}", session.getId(), throwable.getMessage());
    }


}
